package com.iwdnb.gkgz.application.service.source;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.iwdnb.gkgz.application.service.IStockDataSource;
import com.iwdnb.gkgz.application.collect.bean.JuHeStockResult;
import com.iwdnb.gkgz.common.model.dto.Stock;
import com.iwdnb.gkgz.common.model.dto.StockDayData;
import com.iwdnb.gkgz.application.vo.StockType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 聚合股票数据接口
 *
 * @author pengl
 * @date 2020/05/03
 **/
@Component
public class JuHeStockDataSource implements IStockDataSource {
    private static final String BASE_URL = "http://web.juhe.cn:8080/finance/stock/shall";
    private static final String BASE_SZ_URL = "http://web.juhe.cn:8080/finance/stock/szall";

    @Autowired(required = false)
    RestTemplate restTemplate;

    //@Value("${stock.key.juhe}")
    String key;

    @Override
    public List<Stock> getOnlineStockList(int page, int pageSize, StockType type) {
        String baseUrl = StockType.SZ == type ? BASE_SZ_URL : BASE_URL;
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("key", key)
                .queryParam("stock", "") //a表示A股，b表示B股,默认所有
                .queryParam("type", getPageType(pageSize)) //每页返回条数,1(20条默认),2(40条),3(60条),4(80条)
                .queryParam("page", page);//	第几页,默认第1页

        JuHeStockResult result = restTemplate.getForObject(builder.build().encode().toUri(), JuHeStockResult.class);

        JuHeStockResult.ResultBean pageObj = result.getResult();
        List<JuHeStockResult.ResultBean.DataBean> data = pageObj.getData();

        List<Stock> dataList = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            dataList.add(transferStock(data.get(i)));
        }

        return dataList;
    }

    @Override
    public Stock getStock(String code, StockType type) {
        return null;
    }


    @Override
    public List<StockDayData> getStockDataByDate(String code, StockType type, Date startDate, Date endDate) {
        return null;
    }

    private Stock transferStock(JuHeStockResult.ResultBean.DataBean juHeStock){
        Stock stock = new Stock();

        stock.setCode(juHeStock.getCode());
        stock.setMarket(juHeStock.getSymbol().substring(0,2));
//        stock.setType(juHeStock.getCode());
        stock.setName(juHeStock.getName());

        return stock;
    }

    private int getPageType(int pageSize){
        int type = 1;

        if(pageSize >= 20)
            type = 2;

        if(pageSize >= 40)
            type = 3;

        if(pageSize >= 60)
            type = 3;

        if(pageSize >= 80)
            type = 4;

        return type;
    }


}
